<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue监测数据改变的原理_数组</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <!--
        1.Vue会监测data中所有层次的数据
        2.如何监测对象中的数据？
            通过setter实现监测，且要在new vue时就传入要监测的数据
    -->
    <div id="root">
        <h1>学生信息</h1>
        <button @click="student.age++">年龄+1</button>
        <button @click="addSex">添加性别，默认：男</button>
        <button @click="student.sex='未知'">修改性别</button>
        <button @click="addFriend">列表首位添加一个朋友</button>
        <button @click="updateFriend">修改第一个朋友的名字为：张三</button>
        <button @click="addHobby">添加一个爱好</button>
        <button @click="updateHobby">修改第一个爱好为：开车</button>
        <h1>学生姓名：{{student.name}}</h1>
        <h1 v-if="student.sex">性别：{{student.sex}}</h1>
        <h1>学生年龄：{{student.age}}</h1>
        <h1>学生爱好：</h1>
        <ul>
            <li v-for = 'h,index in student.hobby' :key="index">
                {{h}}
            </li>
        </ul>
        <h1>学生朋友：</h1>
        <ul>
            <li v-for = 'f,index in student.friends' :key="index">
                {{f.name}}-{{f.age}}
            </li>
        </ul>
        <button @click = "setInfo">添加属性</button>
    </div>
</body>
    <script type="text/javascript">
        
        const vm = new Vue({
            el:'#root',
            data:function(){
                return{
                    student:{
                        name:'tom',
                        age:18,
                        hobby:['篮球','排球','羽毛球'],                     
                        friends:[
                            {name:'jerry',age:35},
                            {name:'bob',age:56}
                        ]
                    }
                }
            },
            methods:{
                addSex(){
                    Vue.set(this.student,'sex','男')
                    //this.$set(this.student,'sex','男') 上下两个方法都可以
                },
                addFriend(){
                    this.student.friends.unshift({name:'trent',age:29})
                },
                updateFriend(){
                    this.student.friends[0].name = "张三"
                },
                addHobby(){
                    this.student.hobby.push('乒乓球')
                },
                updateHobby(){
                    this.student.hobby.splice(0,1,'开车')
                },
                setInfo(){
                    this.student.hobby.push('乒乓球')
                    this.student.hobby.splice(0,1,'足球')
                }
          }
        })
    </script>
</html>